package com.service.api.google;

// Copyright 2011, Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.


import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.xml.rpc.ServiceException;

import com.google.api.adwords.lib.AdWordsService;
import com.google.api.adwords.lib.AdWordsServiceLogger;
import com.google.api.adwords.lib.AdWordsUser;
import com.google.api.adwords.lib.utils.MapUtils;
import com.google.api.adwords.v201209.cm.ApiException;
import com.google.api.adwords.v201209.cm.Paging;
import com.google.api.adwords.v201209.o.Attribute;
import com.google.api.adwords.v201209.o.AttributeType;
import com.google.api.adwords.v201209.o.IdeaType;
import com.google.api.adwords.v201209.o.LongAttribute;
import com.google.api.adwords.v201209.o.RelatedToQuerySearchParameter;
import com.google.api.adwords.v201209.o.RequestType;
import com.google.api.adwords.v201209.o.SearchParameter;
import com.google.api.adwords.v201209.o.StringAttribute;
import com.google.api.adwords.v201209.o.TargetingIdea;
import com.google.api.adwords.v201209.o.TargetingIdeaPage;
import com.google.api.adwords.v201209.o.TargetingIdeaSelector;
import com.google.api.adwords.v201209.o.TargetingIdeaServiceInterface;
import com.pub.i.AttributesI;
import com.service.vo.KeywordVo;

/**
 * This class gets keywords related to a seed keyword.
 *
 * Tags: related keywords
 *
 * 
 * @author ldmmyx@gmail.com (ivan ling)
 */
public class GetRelatedKeywords implements AttributesI
{
	private int offset	= 0;
	private int limit	= 10;
	
	
	private AdWordsUser user;
	private TargetingIdeaServiceInterface targetingIdeaService;
	
	public GetRelatedKeywords(AdWordsUser user)
	{
		 this.user = user;
	}
	
	public GetRelatedKeywords(String email, String password, String userAgent, String developerToken)
	{
		 user = new AdWordsUser(email, password, userAgent, developerToken);
	}
	
	public void init() throws ServiceException
	{
		targetingIdeaService = user.getService(AdWordsService.V201209.TARGETING_IDEA_SERVICE);
	}
	
	public void setOffset(int offset)
	{
		this.offset	= offset;
	}
	
	public void setLimit(int limit)
	{
		this.limit	= limit;
	}
	

	public List<KeywordVo> getKeywords(String keywords) throws ServiceException, ApiException, RemoteException
	{

		List<KeywordVo> keywordList = null;
		
		// Log SOAP XML request and response.
	    AdWordsServiceLogger.log();

	    // Create seed keyword.
	    String[] arrKeywords = new String[1];
	    
	    arrKeywords[0] = keywords;
	   
	    
	    // Create selector.
	    TargetingIdeaSelector selector = new TargetingIdeaSelector();
	    selector.setRequestType(RequestType.IDEAS);
	    selector.setIdeaType(IdeaType.KEYWORD);
	    selector.setRequestedAttributeTypes(new AttributeType[] {
	    		AttributeType.KEYWORD_TEXT, 
	    		AttributeType.SEARCH_VOLUME, 
	    		AttributeType.TARGETED_MONTHLY_SEARCHES
	    });

	    // Set selector paging (required for targeting idea service).
	    Paging paging = new Paging();
	    paging.setStartIndex(offset);
	    paging.setNumberResults(limit);
	    selector.setPaging(paging);

	    RelatedToQuerySearchParameter relatedToKeywordSearchParameter = new RelatedToQuerySearchParameter();
	    relatedToKeywordSearchParameter.setQueries(arrKeywords);
 	    selector.setSearchParameters(new SearchParameter[] {relatedToKeywordSearchParameter});

	    // Get related keywords. getBulkKeywordIdeas
	    TargetingIdeaPage page = targetingIdeaService.get(selector);
	     
	    TargetingIdea[] targetingIdeas	= page.getEntries();
	    // Display related keywords.
	    if (targetingIdeas != null && targetingIdeas.length > 0) {
	    	keywordList = new ArrayList<KeywordVo>(targetingIdeas.length + 1);
	    	 
	    	Long globalMonthlySearches;
	    	Long averageMonthlySearches;
	    	 
	    	KeywordVo vo;
	    	
	    	StringAttribute keyword;
	    	Map<AttributeType, Attribute> data;
	    	 
	    	 
	    	for (TargetingIdea targetingIdea : targetingIdeas) {
	    		data 	= MapUtils.toMap(targetingIdea.getData());
	    		keyword = (StringAttribute) data.get(AttributeType.KEYWORD_TEXT);
	    		 
	    		globalMonthlySearches 	= ((LongAttribute) data.get(AttributeType.SEARCH_VOLUME)).getValue();
	    		averageMonthlySearches 	= ((LongAttribute) data.get(AttributeType.TARGETED_MONTHLY_SEARCHES)).getValue();
	    		 
	    		vo = new KeywordVo();
	    		
	    		vo.put(AttributesI.GLOBAL_MONTHLY_SEARCHES, globalMonthlySearches.toString());
	    		vo.put(AttributesI.AVERAGE_MONTHLY_SEARCHES, averageMonthlySearches.toString());
	    		
	    		vo.setKeyword(keyword.getValue());
	    		
	    		keywordList.add(vo);
	    		
	    	}
	    } else {
	    	keywordList = new ArrayList<KeywordVo>();
	    	
//	    	System.out.println("No related keywords were found.");
	    }
	     
	    return keywordList;
	}

}
